// ESP01S.c
#include "ESP01S.h"
#include "freertos.h"
#include "semphr.h"
#include "USART.h"
#include "string.h"
#define CLEAR_ARRAY_WITH_LOOP(arr) do { \
    size_t _count = sizeof(arr) / sizeof((arr)[0]); \
    for (size_t _i = 0; _i < _count; _i++) { \
        (arr)[_i] = 0; \
    } \
} while (0)

extern QueueHandle_t queueESP01;   // 用来接受ESP01发送消息的消息队列
extern int GetFromQueue(QueueHandle_t queue, char buf[]);
//此设备用于驱动网卡模块
//连线

/*

*/
/*
	引脚配置宏
	3v3接 3.3V电源
	RST接 3.3V电源正极
	EN接  3.3v电源正极
	IO1   悬空
	IO2   悬空
	ESP_TX针脚接入PA10引脚
	ESP_RX针脚接入PA9引脚
*/
#define ESP_TX_GPIO_PORT           GPIOA
#define ESP_TX_GPIO_PIN            GPIO_Pin_10
#define ESP_RX_GPIO_PORT           GPIOA
#define ESP_RX_GPIO_PIN            GPIO_Pin_9
#define RCC_APBXPeriph_GPIOX       RCC_APB2Periph_GPIOA
#define RCC_APBXPeriph_USARTX      RCC_APB2Periph_USART1

void ESP01S_Init(void) {
    // 开启时钟
    RCC_APB2PeriphClockCmd(RCC_APBXPeriph_USARTX, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APBXPeriph_GPIOX, ENABLE);

    // 初始化引脚
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Pin = ESP_RX_GPIO_PIN;//PA9:接ESP01S_RX
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Pin = ESP_TX_GPIO_PIN ;//PA10:接ESP01S_TX
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    // USART配置
    USART_InitTypeDef USART_InitStructure;
    USART_InitStructure.USART_BaudRate = 115200;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_Init(USART1, &USART_InitStructure);
    // 启动ESP01S

    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
    // NVIC ���ó�ʼ��

    NVIC_InitTypeDef NVIC_InitStructure;
    // ���� NVIC������ HC05���ж�
    NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; // ����HC05���ж�
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 12;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
    USART_Cmd(USART1, ENABLE);

}

// 发送字节
void SendByteToESP01(uint8_t Byte) {
    USART_SendData(USART1, Byte);

    while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}

void SendToESP01S(char *format, ...) {

    char strs[200];
    va_list list;
    va_start(list, format);
    vsprintf(strs, format, list);
    va_end(list);

    for (uint8_t i = 0; strs[i] != '\0'; i++) {
        SendByteToESP01(strs[i]);
    }
}

int ESP01SC_connectWIFI(char *buf, char* wifiname, char* wifipassword) {
    int ret = SendCommandToESP01S(buf, "AT+CWJAP_DEF=\"%s\",\"%s\"\r\n", wifiname, wifipassword); //发送密码
    return ret;
}

int ESP01SC_connectTCP(char *buf, char* SERVERIP, char*  SERVERPORT) {
    int ret = SendCommandToESP01S(buf, "AT+CIPSTART=\"TCP\",\"%s\",%s\r\n", SERVERIP, SERVERPORT); //发送IP和端口
    CLEAR_ARRAY_WITH_LOOP(buf);

    ret = SendCommandToESP01S(buf, "AT+CIPMODE=1\r\n");
    CLEAR_ARRAY_WITH_LOOP(buf);

    ret = SendCommandToESP01S(buf, "AT+CIPSEND\r\n");
    CLEAR_ARRAY_WITH_LOOP(buf);
    return ret;
}

int ESP01SC_disconnectTCP(char *buf) {
    vTaskDelay(1000);
    SendToESP01S("+++");
    vTaskDelay(1000);

    int ret = SendCommandToESP01S(buf, "AT+CIPMODE=0\r\n"); //关闭透传模式
    CLEAR_ARRAY_WITH_LOOP(buf);

    ret = SendCommandToESP01S(buf, "AT+CIPCLOSE\r\n"); //关闭TCP连接
    CLEAR_ARRAY_WITH_LOOP(buf);
    return ret;
}

int SendCommandToESP01S(char *buf, char *format, ...) {

    char strs[200];
    va_list list;
    va_start(list, format);
    vsprintf(strs, format, list);
    va_end(list);

    for (uint8_t i = 0; strs[i] != '\0'; i++) {
        SendByteToESP01(strs[i]);
    }

    return GetFromQueue(queueESP01, buf);
}

uint32_t myhtonl(uint32_t value) {
    // 按字节反转顺序
    return ((value & 0xFF) << 24) |
           ((value & 0xFF00) << 8) |
           ((value >> 8) & 0xFF00) |
           ((value >> 24) & 0xFF);
}

int SendMessageToESP01S(char Message[]) {
    char buf[200] = {0};
    char Stm32POST[] = "POST /stm32 HTTP/1.1\r\n\r\n";
    int num = strlen(Message) + strlen(Stm32POST);
    sprintf(buf, "%c%c%c%c%s%s!", *(((char*)&num)), *(((char*)&num) +1), *(((char*)&num) +2), *(((char*)&num) +3),
            Stm32POST, Message);

    for (uint8_t i = 0; i < 4 + num; i++) {
        SendByteToESP01(
            buf[i]);//注意，此处一定要用单字节send而不能用Printf1，那个是按字符串打印，遇到\0就会停止，而数字转为字符串，很容易有\0
    }

    return num;
}

